const WxUtil = require('../../../utils/WxUtil.js')
const apiUrl = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_imagetranslate";
const initImg = "https://yyb.gtimg.com/aiplat/static/ai-demo/large/imagetranslate-demo2.jpg";
const app = getApp();
Page({
  data: {
    imgPath: initImg,
    image_records: [],
    //翻译类型
    translateType:"e2h"
  },

  //拍照翻译
  photograph() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePath = res.tempFilePaths[0]

        that.setData({
          imgPath: tempFilePath,
          image_records: []
        });

        wx.showLoading();
        
        let image64 = wx.getFileSystemManager().readFileSync(tempFilePath, 'base64') 
        
        let time = new Date().getTime();
        let app_id = app.globalData.aiAppId;
        let time_stamp = parseInt(time / 1000);
        let nonce_str = WxUtil.getRandStr();

        //let session_id = app.globalData.openid.substring(0, 6) + time;
        let session_id = time;
        if (app.globalData.openid)
        {
          session_id = app.globalData.openid.substring(0, 6) + session_id;
        }
        let source = "en";
        let target = "zh";

        if (that.data.translateType=="h2e")
        {
          source = "zh";
          target = "en";
        }

        let params = {
          app_id: app_id,
          time_stamp: time_stamp,
          nonce_str: nonce_str,
          image: image64,
          session_id: session_id,
          scene: "doc",
          source: source,
          target: target
        }

        let sign = WxUtil.getReqSign(params);
        params.sign = sign;

        //调用图片翻译接口
        wx.request({
          url: apiUrl,
          method:'post',
          data: params,
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            console.info("=========图片翻译完毕========");
            console.info(res);
            that.setData({
              image_records: res.data.data.image_records
            });      
            wx.hideLoading();      
          },
          fail: function (error) {
            console.error(error)
            wx.hideLoading(); 
          }
        })
      }
    }) 
  },

  radioChange: function(e) {
    var translateType = e.detail.value;
    console.info("translateType=====" + translateType);
    
    this.setData({
      translateType: translateType
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})